package com.cloudy.core.thrift.server;

import com.cloudy.core.common.ThriftConstants;
import com.cloudy.core.common.ThriftProcessorManager;
import com.cloudy.core.common.ip.AddressIp;
import com.cloudy.core.common.ip.IAddressIp;
import com.cloudy.core.thrift.zookeeper.server.ThriftServerAddressRegister;
import org.apache.thrift.TProcessor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 *  thrift服务端服务提供类
 *     通过该类 提供对thrift实现接口service的注入管理
 *     使用 TMultiplexedProcessor 方式进行多processor进行管理,通过类名(不包括目录)标示,所有service类名(不包括目录)不能一样
 * Created by cloudy.xie on 16/11/18.
 */
public class ThriftServerSupport implements InitializingBean {
    /////服务配置参数 提供getter setter
    // 服务注册本机端口
    private Integer port ;

    ////// 服务使用参数 从构造函数赋值
    private ThriftServerBootstrap thriftServerBootstrap;
    private ThriftProcessorManager thriftProcessorManager;
    //服务注册
    private ThriftServerAddressRegister thriftServerAddressRegister;
    protected IAddressIp addressIp;

    public ThriftServerSupport(){
        thriftProcessorManager = ThriftProcessorManager.getInstance();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String,TProcessor> prcessorMap = thriftProcessorManager.getProcessor();
        thriftServerBootstrap = new ThriftServerBootstrap(prcessorMap,port);

        if (addressIp == null) {
            addressIp = new AddressIp();
        }
        String serverIP = addressIp.getServerIp();
        if (StringUtils.isEmpty(serverIP)) {
//            throw new ThriftException("cant find server ip...");
        }

        int weight = 1;
        String version="1.0.0";
        String hostname = serverIP + ":" + port + ":" + weight;

        //启动服务
        Thread thread = new Thread(thriftServerBootstrap);
        thread.start();

        // 注册服务
        if (thriftServerAddressRegister != null) {
            thriftServerAddressRegister.register(ThriftConstants.SERVICE_PACKAGE, version, hostname);
        }
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public void setThriftServerAddressRegister(ThriftServerAddressRegister thriftServerAddressRegister) {
        this.thriftServerAddressRegister = thriftServerAddressRegister;
    }

    public void close() {
        thriftServerBootstrap.close();
    }
}
